package com.dayuanit.dy15.spider.runnable;

import com.dayuanit.dy15.spider.util.SleepUtil;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class DownLoadRunnable implements Runnable {
    private String url;
    private String fileName;

    public DownLoadRunnable (String url, String fileName) {
        this.url = url;
        this.fileName = fileName;
    }

    @Override
    public void run() {
        URL url = null;
        try {
            url = new URL(this.url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try (InputStream is = url.openStream();
              FileOutputStream fos = new FileOutputStream("D:/dayuanit/15/book-img/" + fileName);) {
            byte[] buff = new byte[1024];
            int length = -1;
            while (-1 != (length = is.read(buff))) {
                fos.write(buff, 0, length);
                fos.flush();
            }

            System.out.println(fileName + "下载完毕");
            SleepUtil.sleep();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
